package com.yyx.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yyx.common.R;
import com.yyx.constant.DishConstant;
import com.yyx.entity.Category;
import com.yyx.entity.Dish;
import com.yyx.entity.dto.DishDto;
import com.yyx.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 前端控制器
 * </p>
 *
 * @author yeyinxuan
 * @since 2023-07-31
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    DishService dishService;


    @GetMapping("/page")
    public R<Page> page(int page, int pageSize,String name){
        Page<DishDto> c = dishService.selectpage(page,pageSize,name);
//        log.info(String.valueOf(this));
        return R.success(c);
    }

    @PostMapping
    public R saveWithflavor(@RequestBody DishDto dishDto){
        Boolean t = dishService.save(dishDto);
        if(t){
            return R.success("操作成功");
        }
        else {
            return R.error("操作失败");
        }

    }

    @GetMapping("/{id}")
    public R<DishDto> getDishByid(@PathVariable("id") Long id ){
        DishDto dish = dishService.getDishDtoByid(id);
        return R.success(dish);
    }


    @PutMapping
    public R updateDish(@RequestBody DishDto dishDto){
        dishService.save(dishDto);
        return R.success("修改成功");
    }

    @GetMapping("list")
    public R<List<DishDto>> list(Dish dish){
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus, DishConstant.STATUS_NORMAL);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        List<DishDto> dishDtos = list.stream().map((item -> {
            DishDto dishDto = dishService.getDishDtoByid(item.getId());
            return dishDto;
        })).collect(Collectors.toList());
        return R.success(dishDtos);
    }

}
